package com.yu1996.gulimall.ware.service.impl;

import com.yu1996.common.constant.WareConstant;
import com.yu1996.common.constant.WareConstant.PurchaseDetailStatusEnum;
import com.yu1996.common.constant.WareConstant.PurchaseStatusEnum;
import com.yu1996.gulimall.ware.entity.PurchaseDetailEntity;
import com.yu1996.gulimall.ware.service.PurchaseDetailService;
import com.yu1996.gulimall.ware.service.WareSkuService;
import com.yu1996.gulimall.ware.vo.MergeVo;
import com.yu1996.gulimall.ware.vo.PurchaseDoneVo;
import com.yu1996.gulimall.ware.vo.PurchaseItemDoneVo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu1996.common.utils.PageUtils;
import com.yu1996.common.utils.Query;

import com.yu1996.gulimall.ware.dao.PurchaseDao;
import com.yu1996.gulimall.ware.entity.PurchaseEntity;
import com.yu1996.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity>
    implements PurchaseService {

  @Autowired private PurchaseDetailService purchaseDetailService;
  @Autowired private WareSkuService wareSkuService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<PurchaseEntity> page =
        this.page(new Query<PurchaseEntity>().getPage(params), new QueryWrapper<PurchaseEntity>());

    return new PageUtils(page);
  }

  /**
   * 查询可以合并的采购单
   *
   * @param params
   * @return
   */
  @Override
  public PageUtils unreceivePurchase(Map<String, Object> params) {
    IPage<PurchaseEntity> page =
        this.page(
            new Query<PurchaseEntity>().getPage(params),
            new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1));

    return new PageUtils(page);
  }
  /** 合并采购需求 */
  @Transactional
  @Override
  public void mergePurchase(MergeVo mergeVo) {
    Long purchaseId = mergeVo.getPurchaseId();
    if (StringUtils.isEmpty(purchaseId)) {
      PurchaseEntity purchaseEntity = new PurchaseEntity();
      purchaseEntity.setCreateTime(new Date());
      purchaseEntity.setUpdateTime(new Date());
      purchaseEntity.setStatus(PurchaseStatusEnum.CREATED.getCode());
      this.save(purchaseEntity);
      purchaseId = purchaseEntity.getId();
    }
    List<Long> items = mergeVo.getItems();
    Long finalPurchaseId = purchaseId;
    List<PurchaseDetailEntity> collect =
        items.stream()
            .filter(
                // 判断采购单的状态是否可以合并
                (filte) -> {
                  PurchaseDetailEntity byId = purchaseDetailService.getById(filte);
                  if (byId.getStatus() == PurchaseDetailStatusEnum.CREATED.getCode()
                      || byId.getStatus() == PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                    return true;
                  } else {
                    return false;
                  }
                })
            .map(
                item -> {
                  PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                  purchaseDetailEntity.setId(item);
                  purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                  purchaseDetailEntity.setStatus(PurchaseDetailStatusEnum.ASSIGNED.getCode());
                  return purchaseDetailEntity;
                })
            .collect(Collectors.toList());
    purchaseDetailService.updateBatchById(collect);
    PurchaseEntity purchaseEntity1 = new PurchaseEntity();
    purchaseEntity1.setUpdateTime(new Date());
    purchaseEntity1.setId(finalPurchaseId);
    this.updateById(purchaseEntity1);
  }
  /** 领取采购单 */
  @Transactional
  @Override
  public void received(List<Long> ids) {
    // 1、确认采购单是新建或者已分配状态
    List<PurchaseEntity> collect =
        ids.stream()
            .map(
                item -> {
                  PurchaseEntity byId = this.getById(item);
                  return byId;
                })
            .filter(
                fit -> {
                  if (fit.getStatus() == PurchaseStatusEnum.CREATED.getCode()
                      || fit.getStatus() == PurchaseStatusEnum.ASSIGNED.getCode()) {
                    return true;
                  } else {
                    return false;
                  }
                })
            .map(
                (map1 -> {
                  map1.setStatus(PurchaseStatusEnum.RECEIVE.getCode());
                  map1.setUpdateTime(new Date());
                  return map1;
                }))
            .collect(Collectors.toList());
    // 2、改变采购单的状态
    this.updateBatchById(collect);
    collect.forEach(
        entity -> {
          // 获得所有的采购项
          List<PurchaseDetailEntity> detailEntities1 =
              purchaseDetailService.listDetailByPurchaseId(entity.getId());

          // 3、改变采购项的状态
          List<PurchaseDetailEntity> collect1 =
              detailEntities1.stream()
                  .map(
                      detailEntitie -> {
                        detailEntitie.setStatus(PurchaseDetailStatusEnum.BUYING.getCode());
                        return detailEntitie;
                      })
                  .collect(Collectors.toList());

          purchaseDetailService.updateBatchById(collect1);
        });
  }
  /** 完成采购单 */
  @Transactional
  @Override
  public void done(PurchaseDoneVo vo) {
    PurchaseEntity purchase = this.getById(vo.getId());
    boolean flag = true; // 标记是否所有的采购项都成功了
    List<PurchaseItemDoneVo> items = vo.getItems();
    ArrayList<PurchaseDetailEntity> detailEntities = new ArrayList<>();

    for (PurchaseItemDoneVo item : items) {
      PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
      // 1、改变采购项的状态
      if (item.getStatus() == PurchaseDetailStatusEnum.HSAERROR.getCode()) {
        detailEntity.setStatus(PurchaseDetailStatusEnum.HSAERROR.getCode());
        flag = false;
      } else {
        detailEntity.setStatus(PurchaseDetailStatusEnum.FINISH.getCode());
        // 3、成功采购的商品入库
        PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
        wareSkuService.addStock(byId.getSkuId(), byId.getWareId(), byId.getSkuNum());
      }
      detailEntity.setId(item.getItemId());
      detailEntities.add(detailEntity);
    }
    purchaseDetailService.updateBatchById(detailEntities);
    // 2、改变采购单的状态
    if (flag) {
      // 采购成功
      purchase.setStatus(PurchaseStatusEnum.FINISH.getCode());
    } else {
      // 采购失败
      purchase.setStatus(PurchaseStatusEnum.HSAERROR.getCode());
    }
    purchase.setUpdateTime(new Date());
    this.updateById(purchase);
  }
}
